package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author atguigu-mqx
 * @ClassName AccountRecevier
 * @description: TODO
 * @date 2024年09月21日
 * @version: 1.0
 */
@Component
@Slf4j
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;

    /**
     * 监听充值支付成功消息
     * @param orderNo
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_RECHARGE_PAY_SUCCESS,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ORDER),
            key = MqConst.ROUTING_RECHARGE_PAY_SUCCESS
    ))
    public void rechargePaySuccess(String orderNo, Message message , Channel channel){
        try {
            //  判断 orderNo 是否存在
            if (!StringUtils.isEmpty(orderNo)){
                //  调用服务层方法: recharge_info.recharge_status; user_account.total_amount;available_amount; user_account_detail-记录账户变化
                userAccountService.rechargePaySuccess(orderNo);
            }
        } catch (Exception e) {
            log.error("消费异常："+e.getMessage());
        }
        //  开启手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }
    /**
     * 监听用户发送消息，初始化账户信息
     * @param userId
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void userRegister(Long userId, Message message , Channel channel){
        System.out.println("用户注册成功，用户id："+userId);
        try {
            //  判断userId 是否存在
            if (null != userId){
                //  调用服务层方法
                userAccountService.initUserAccount(userId);
            }
        } catch (Exception e) {
            //  第三个参数，是否重回队列，还可以借助redis 计算重回次数，如果到达上线，直接采用异常消息表记录、人工处理！
            //  channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            log.error("消费异常："+e.getMessage());
        }
        //  开启手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }

}
